﻿#include "widget.h"
#include "ui_widget.h"
#include <QUrlQuery>
#include <QNetworkReply>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    QAudioFormat format;
    format.setSampleRate(16000);//设置声音的采样频率
    format.setChannelCount(1);//设置单声道
    format.setSampleSize(16);//16位深
    format.setSampleType(QAudioFormat::SignedInt);
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setCodec("audio/pcm");

    recorder = new QAudioInput(format, this);
    player = new QAudioOutput(format, this);
    connect(player, &QAudioOutput::stateChanged, this, &Widget::play_state_slot);

    bds = new BaiduSpeech(this, "rKCHBLmYiFPuCQTS0HttLbUD", "037dc446820ec143d1628c20146b9d34");
    connect(bds, &BaiduSpeech::doneASR, this, &Widget::asr_finished_slot);
    connect(bds, &BaiduSpeech::doneTTS, this, &Widget::tts_finished_slot);

    client = new QNetworkAccessManager(this);
    connect(client, &QNetworkAccessManager::finished, this, &Widget::on_reply);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_talkButton_toggled(bool checked)
{
    if (checked) {//开始录音
        ui->talkButton->setText("Stop");
        asrbuf = new QBuffer;
        asrbuf->open(QIODevice::ReadWrite);
        recorder->start(asrbuf);
    }
    else {//停止录音
        ui->talkButton->setText("Talk");
        recorder->stop();
        if (!asrbuf->size())
        {
            asrbuf->deleteLater();
            return;
        }
        bds->doASR(asrbuf->data());
    }
}

void Widget::asr_finished_slot()
{
    if (bds->message().size())
    {
        ui->textBrowser->append("我：" + bds->message());

        QUrlQuery params;
        params.addQueryItem("cmd", "chat");
        params.addQueryItem("appid", "22b4a23787f0f249b1c8f3a04ade8c09");
        params.addQueryItem("userid", "liuyu");
        params.addQueryItem("text", bds->message());

        QNetworkRequest request(QUrl("http://idc.emotibot.com/api/ApiKey/openapi.php"));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

        client->post(request, params.toString(QUrl::FullyEncoded).toUtf8());
    }
    asrbuf->deleteLater();
}

void Widget::tts_finished_slot()
{
    if (!bds->audio().size())
    {
        return;
    }
    ttsbuf = new QBuffer;
    ttsbuf->open(QIODevice::ReadWrite);
    ttsbuf->write(bds->audio());
    ttsbuf->reset();

    player->start(ttsbuf);
}

void Widget::play_state_slot(QAudio::State s)
{
    if (s == QAudio::IdleState) {
        player->stop();
        ttsbuf->close();
        ttsbuf->deleteLater();
    }
}

void Widget::on_reply(QNetworkReply* reply)
{
    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
    if (json["return"].toInt()) {
        ui->textBrowser->append("错误：" + json["return_message"].toString());
    }
    else {
        QString msg = "";
        foreach (const QJsonValue &i, json["data"].toArray()) {
            if (i["type"] == "text") {
                msg += i["value"].toString();
            }
        }
        bds->doTTS(msg);
        ui->textBrowser->append("卡卡：" + msg);
    }
    reply->deleteLater();
}
